
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.Place;
import com.cmc.dao.PlaceDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class PlaceDaoHibernate extends BaseDaoHibernate implements PlaceDao {

    /**
     * @see com.cmc.dao.PlaceDao#getPlaces(com.cmc.model.Place)
     */
    public List getPlaces(final Place place) {
        //return getHibernateTemplate().find("from Place");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (place == null) {
            return getHibernateTemplate().find("from Place");
        } else {
            // filter on properties set in the place
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(place).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Place.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.PlaceDao#getPlace(Long id)
     */
    public Place getPlace(final Long id) {
        Place place = (Place) getHibernateTemplate().get(Place.class, id);
        if (place == null) {
            log.warn("uh oh, place with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Place.class, id);
        }

        return place;
    }

    /**
     * @see com.cmc.dao.PlaceDao#savePlace(Place place)
     */    
    public void savePlace(final Place place) {
        getHibernateTemplate().saveOrUpdate(place);
    }

    /**
     * @see com.cmc.dao.PlaceDao#removePlace(Long id)
     */
    public void removePlace(final Long id) {
        getHibernateTemplate().delete(getPlace(id));
    }
}
